package es.ceura.wilder.parsers;

import es.ceura.wilder.configuration.Config;
import es.ceura.wilder.datastructures.response.HTTPCode;
import es.ceura.wilder.datastructures.request.HTTPRequest;
import es.ceura.wilder.datastructures.response.HTTPResponse;
import es.ceura.wilder.datastructures.Header;
import es.ceura.wilder.datastructures.HeaderType;
import es.ceura.wilder.datastructures.response.ResponseStatusLine;
import es.ceura.wilder.resources.DeniedAccesException;
import es.ceura.wilder.resources.HTTPResource;
import es.ceura.wilder.resources.InvalidResourceRequestException;
import es.ceura.wilder.resources.ResourceGetter;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.HashMap;

/**
 *
 * @author Jorge Madrid
 */
public class HTTPResponseParser {

    private HTTPRequest httpRequest;
    private ResourceGetter resourceGetter;

    public HTTPResponseParser() {
        resourceGetter = new ResourceGetter();
    }

    public HTTPResponse createHTTPResponse(HTTPRequest httpRequest)
            throws FileNotFoundException, IOException, DeniedAccesException,
            InvalidResourceRequestException {
        this.httpRequest = httpRequest;
        HTTPResponse response;
        HTTPResource resource = resourceGetter.
                getResource(httpRequest.getStatusLine().getResourcePath());
        ResponseStatusLine statusLine = createStatusLine(HTTPCode.HTTP_200);
        HashMap<HeaderType, Header> headerMap = createHeaders(resource);

        response = new HTTPResponse(statusLine, headerMap, resource.getData());

        return response;
    }

    public HTTPResponse createHTTPNotFound(HTTPRequest httpRequest) throws
            FileNotFoundException, IOException, DeniedAccesException, InvalidResourceRequestException {
        this.httpRequest = httpRequest;
        HTTPResponse response;
        ResponseStatusLine statusLine = createStatusLine(HTTPCode.HTTP_404);
        HTTPResource resource = resourceGetter.
                getResource("/" + Config.INSTANCE.getConfigVar(Config._404));
        response = new HTTPResponse(statusLine, new HashMap<HeaderType, Header>(), resource.getData());
        return response;
    }

    private ResponseStatusLine createStatusLine(HTTPCode code) {
        ResponseStatusLine statusLine;
        statusLine = new ResponseStatusLine(httpRequest.getStatusLine().getHttpVersion());
        statusLine.setCode(code);
        return statusLine;
    }

    private HashMap<HeaderType, Header> createHeaders(HTTPResource resource) {
        HashMap<HeaderType, Header> headerMap = new HashMap<>();

        // headerMap.put(HeaderType.CONTENT_TYPE, new Header(resource.getContentType()));
        headerMap.put(HeaderType.CONTENT_LENGTH, new Header(Long.toString(
                resource.getDataSize())));

        return headerMap;
    }
}
